module namespace auth = 'http://twittercharts.uzh.ch/authorization';

import module namespace oac = "http://www.28msec.com/modules/oauth/commons";
import module namespace http = "http://www.28msec.com/modules/http";
import module namespace cookie = "http://www.28msec.com/modules/http/cookie";

import schema namespace oa = "http://www.28msec.com/modules/oauth/client";

(: customer key and secret of our Twitter application :)
declare variable $auth:config-twitter := oac:config-twitter(
    "xAOjnQKQZqYXz6hRVv6UBQ",
    "g2BBlD90cGgYox5fD3M3BzepGUYKgN6eiNbG72kpLdg",
    "http://twitter-charts.my28msec.com/authorization/callback"
);

(:
 : Initializes the log-in process.
 :)
declare sequential function auth:log-in()
{
    oac:init(
        $auth:config-twitter
    )
};

(:
 : The user is redirected to this function when having granted access to our
 : application.
 :)
declare sequential function auth:callback()
{
    oac:callback(
        $auth:config-twitter
    ),
    http:send-redirect("session")
};

(:
 : Saves the user's ID and Twitter username in a session an redirects him to
 : his Twitter Charts profile. 
 :)
declare sequential function auth:session()
{
    declare $http-request := validate {
        <oa:http-request>
            <oa:target-url>http://twitter.com/account/verify_credentials.xml</oa:target-url>
        </oa:http-request>
    };
    declare $response := oac:resource($auth:config-twitter, $http-request)/oa:payload/node();
    declare $user-id := $response/id/text();
    declare $screen-name := $response/screen_name/text();
  
    cookie:create-session(
        <user>
            <id>{$user-id}</id>
            <screen_name>{$screen-name}</screen_name>
        </user>,
        fn:current-dateTime() + (<period>P1D</period> cast as xs:duration),
        "/"
    ),
    http:send-redirect("/default/show-profile")
};

(:
 : Deletes the session of a logged in user.
 :)
declare sequential function auth:log-out()
{
    cookie:delete-session("/"),
    http:send-redirect("/index.html")
};
